<template>
  <div class="user-profile">
    <h2>个人信息</h2>
    <div v-if="error" class="error-message">{{ error }}</div>
    <form v-if="user" @submit.prevent="handleSubmit" class="profile-form" :class="{ 'loading': isLoading }">
      <div class="form-item">
        <label>账号</label>
        <input type="text" v-model="user.account" disabled />
      </div>
      <div class="form-item">
        <label>昵称</label>
        <input type="text" v-model="user.name" required />
      </div>
      <div class="form-actions">
        <button type="submit" class="btn-save" :disabled="isLoading">
          <loading-spinner v-if="isLoading" text="保存中..." />
          <span v-else>保存修改</span>
        </button>
      </div>
    </form>

    <div class="section">
      <h3>修改密码</h3>
      <form @submit.prevent="handlePasswordChange" class="password-form">
        <div class="form-item">
          <label>当前密码</label>
          <input type="password" v-model="passwordForm.oldPassword" required />
        </div>
        <div class="form-item">
          <label>新密码</label>
          <input type="password" v-model="passwordForm.newPassword" required />
          <div class="password-hint">密码至少需要6个字符</div>
        </div>
        <div class="form-item">
          <label>确认新密码</label>
          <input type="password" v-model="passwordForm.confirmPassword" required />
        </div>
        <div class="form-actions">
          <button type="submit" class="btn-change">修改密码</button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import LoadingSpinner from '../components/LoadingSpinner.vue'
import { getUserInfo, updateUser, changePassword } from '../api/user'

const store = useStore()
const router = useRouter()
const user = ref(null)
const error = ref('')
const isLoading = ref(false)
const isChangingPassword = ref(false)

const passwordForm = ref({
  account: '',
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const fetchUserInfo = async () => {
  try {
    console.log('Fetching user info...')
    const response = await getUserInfo(store.state.token)
    console.log('User info response:', response)
    
    if (response.code === 200) {
      user.value = response.data
      passwordForm.value.account = response.data.account
    } else {
      error.value = response.msg
    }
  } catch (err) {
    console.error('Fetch user info error:', err)
    error.value = '获取用户信息失败'
  }
}

const handleSubmit = async () => {
  if (isLoading.value) return
  error.value = ''
  isLoading.value = true

  try {
    const response = await updateUser(user.value)
    if (response.code === 200) {
      store.commit('setUser', user.value)
      alert('保存成功')
    } else {
      error.value = response.msg
    }
  } catch (err) {
    console.error('Update user error:', err)
    error.value = err.message || '更新失败'
  } finally {
    isLoading.value = false
  }
}

const validatePasswordForm = () => {
  if (passwordForm.value.newPassword.length < 6) {
    error.value = '新密码至少需要6个字符'
    return false
  }
  if (passwordForm.value.newPassword !== passwordForm.value.confirmPassword) {
    error.value = '两次输入的新密码不一致'
    return false
  }
  return true
}

const handlePasswordChange = async () => {
  if (isChangingPassword.value) return
  error.value = ''
  
  if (!validatePasswordForm()) return
  
  isChangingPassword.value = true
  try {
    const response = await changePassword(passwordForm.value)
    if (response.code === 200) {
      alert('密码修改成功，请重新登录')
      store.commit('logout')
      router.push('/login')
    } else {
      error.value = response.msg
    }
  } catch (err) {
    console.error('Change password error:', err)
    error.value = err.message || '修改密码失败'
  } finally {
    isChangingPassword.value = false
  }
}

onMounted(() => {
  fetchUserInfo()
})
</script>

<style scoped>
.user-profile {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
}

.section {
  margin-top: 40px;
}

.profile-form, .password-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
  margin-top: 20px;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

input, textarea {
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

input:disabled {
  background-color: #f5f5f5;
  cursor: not-allowed;
}

.form-actions {
  display: flex;
  gap: 10px;
}

.btn-save, .btn-change {
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  background-color: #4CAF50;
  color: white;
  border: none;
}

.btn-save:disabled, .btn-change:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

.error-message {
  color: #f44336;
  margin-bottom: 15px;
  padding: 10px;
  background-color: #ffebee;
  border-radius: 4px;
  font-size: 14px;
}

.loading {
  opacity: 0.7;
  pointer-events: none;
}
</style> 